//
//  NotificationViewController.m
//  JiuJiuShangCheng
//
//  Created by jiujiukeji on 2018/7/6.
//  Copyright © 2018年 jiujiukeji. All rights reserved.
//

#import "MessageViewController.h"
#import "NotificationTableViewCell.h"
#import "MessageDetailViewController.h"

@interface MessageViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *btnArray;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, strong) NSString *status;

@end

@implementation MessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColorWhite;
    [self loadBaseTitleLable:@"消息"];
    [self setUpUI];
    self.currentPage = 1;
    self.pageSize = 20;
    self.status = @"0";
    // 请求数据
    [self getGoodsListData];
}
#pragma mark - 我的消息列表
- (void)getGoodsListData
{
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/member.ashx?action=smslist&companyid=%@&code=%@&timestamp=%@&status=%@&pagesize=%@&pageindex=1",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp],self.status,[NSString stringWithFormat:@"%ld",(long)self.pageSize]] parameters:nil success:^(id responseObject) {
        [self.tableView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:self.view];
        self.dataArray = [NSMutableArray array];
        self.currentPage = 1;
        if ([responseObject[@"status"] intValue] == 1) {
            NSArray *array = responseObject[@"list"];
            for (NSDictionary *dic in array) {
                [self.dataArray addObject:dic];
            }
        }
        NSInteger i = [responseObject[@"count"] intValue]/self.pageSize;
        NSInteger j = [responseObject[@"count"] intValue]%self.pageSize;
        NSInteger n = 0;
        if (j > 0) {
            n = i+1;
        } else {
            n = i;
        }
        if (n<2) {
            self.tableView.mj_footer.hidden = YES;
        } else {
            self.tableView.mj_footer.hidden = NO;
        }
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        [self.tableView.mj_header endRefreshing];
    }];
}
- (void)getGoodsListDataMore
{
    self.currentPage++;
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/member.ashx?action=smslist&companyid=%@&code=%@&timestamp=%@&status=%@&pagesize=%@&pageindex=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp],self.status,[NSString stringWithFormat:@"%ld",(long)self.pageSize],[NSString stringWithFormat:@"%ld",(long)self.currentPage]] parameters:nil success:^(id responseObject) {
        [self.tableView.mj_footer endRefreshing];
        [MBProgressHUD hideHUDForView:self.view];
        if ([responseObject[@"status"] intValue] == 1) {
            
            NSInteger i = [responseObject[@"count"] intValue]/self.pageSize;
            NSInteger j = [responseObject[@"count"] intValue]%self.pageSize;
            NSInteger n = 0;
            if (j > 0) {
                n = i+1;
            } else {
                n = i;
            }
            if (self.currentPage > n) {
                self.currentPage--;
                self.tableView.mj_footer.hidden = YES;
            } else {
                self.tableView.mj_footer.hidden = NO;
                NSArray *array = responseObject[@"list"];
                for (NSDictionary *dic in array) {
                    [self.dataArray addObject:dic];
                }
                [self.tableView reloadData];
            }
        } else {
            self.currentPage--;
            self.tableView.mj_footer.hidden = YES;
        }
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        [self.tableView.mj_footer endRefreshing];
    }];
}
- (void)setUpUI
{
    UIButton *btn1 = [UIButton buttonWithTitle:@"未读通知" fontSize:13 titleColor:UIColorWhite background:UIColorFromRGB(0xfbc865) cornerRadius:0];
    [self.view addSubview:btn1];
    [btn1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.top.equalTo(self.view).offset(SafeAreaTopHeight);
        make.size.mas_offset(CGSizeMake(kScreenWidth/2, rateHeight(90)));
    }];
    UIButton *btn2 = [UIButton buttonWithTitle:@"已读通知" fontSize:13 titleColor:UIColorFromRGB(0x909090) background:UIColorFromRGB(0xf5f5f5) cornerRadius:0];
    [self.view addSubview:btn2];
    [btn2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(SafeAreaTopHeight);
        make.size.mas_offset(CGSizeMake(kScreenWidth/2, rateHeight(90)));
    }];
    self.btnArray = [NSMutableArray array];
    btn1.tag = 0;
    btn2.tag = 1;
    [self.btnArray addObject:btn1];
    [self.btnArray addObject:btn2];
    [btn1 addTarget:self action:@selector(actionSelect:) forControlEvents:(UIControlEventTouchUpInside)];
    [btn2 addTarget:self action:@selector(actionSelect:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.view addSubview:self.tableView];
}
- (void)actionSelect:(UIButton *)btn
{
    self.status = [NSString stringWithFormat:@"%ld",(long)btn.tag];
    for (UIButton *button in self.btnArray) {
        if (button.tag == btn.tag) {
            [button setTitleColor:UIColorWhite forState:(UIControlStateNormal)];
            [button setBackgroundImage:[UIImage createImageWithColor:UIColorFromRGB(0xfbc865)] forState:UIControlStateNormal];
        } else {
            [button setTitleColor:UIColorFromRGB(0x909090) forState:(UIControlStateNormal)];
            [button setBackgroundImage:[UIImage createImageWithColor:UIColorFromRGB(0xf5f5f5)] forState:UIControlStateNormal];
        }
    }
    [self getGoodsListData];
}

#pragma mark - tableView delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NotificationTableViewCell *cell = [[NotificationTableViewCell alloc] init];
    if (_dataArray.count != 0) {
        NSDictionary *dic = _dataArray[indexPath.row];
        cell.titleLB.text = dic[@"smsTitle"];
        cell.timeLB.text = dic[@"smsAddtime"];
    }
    cell.selectionStyle = NO;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return rateHeight(140);
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_dataArray.count != 0) {
        NSDictionary *dic = _dataArray[indexPath.row];
        MessageDetailViewController *messageVC = [[MessageDetailViewController alloc] init];
        messageVC.smsid = dic[@"smsId"];
        [self.navigationController pushViewController:messageVC animated:YES];
    }
}
#pragma mark - 删除
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
// 定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}
// 进入编辑模式，按下出现的编辑按钮后,进行删除操作
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        if (_dataArray.count != 0) {
            NSDictionary *dic = _dataArray[indexPath.row];
            NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
            [MBProgressHUD showMessage:nil toView:self.view];
            [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/member.ashx?action=smsdelete&companyid=%@&code=%@&timestamp=%@&smsid=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp],dic[@"smsId"]] parameters:nil success:^(id responseObject) {
                [MBProgressHUD hideHUDForView:self.view];
                if ([responseObject[@"status"] intValue] == 1) {
                    [self getGoodsListData];
                }
                
            } failure:^(NSError *error) {
                [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
            }];
        }
    }
}
// 修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight+rateHeight(90), kScreenWidth, kScreenHeight-SafeAreaTopHeight-SafeAreaBottomHeight-rateHeight(90)) style:(UITableViewStyleGrouped)];
        _tableView.backgroundColor = UIColorWhite;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        WeakSelf
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf getGoodsListData];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [weakSelf getGoodsListDataMore];
        }];
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
